import { http } from '@/api'
import {getToken, setToken, removeToken, getUserInfo, setUserInfo, removeUserInfo} from '@/utils/auth'

const getDefaultState = () => {
  console.log(getUserInfo())
  return {
    token: getToken(),
    userInfo: getUserInfo(),
    permission: []
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_PERMISSION: (state, permission) => {
    state.permission = permission
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      http.login({ username: username.trim(), password: password }).then(data => {
        commit('SET_TOKEN', data.accessToken)
        commit('SET_PERMISSION', data.permissions)
        setToken(data.accessToken)
        setUserInfo({
          ...data,
          username: username.trim()
        })
        commit('SET_USERINFO', {
          ...data,
          username: username.trim()
        })
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      console.log(state.userInfo.username)
      http.logout(state.userInfo.username).then(() => {
        removeToken() // must remove  token  first
        commit('RESET_STATE')
        resolve()
      }).catch(error => { reject(error) })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeUserInfo()
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

